//
//  LLPlayMusicViewController.swift
//  新印象
//
//  Created by wyl on 2016/12/22.
//  Copyright © 2016年 魏延龙. All rights reserved.
//

import UIKit

class LLPlayMusicViewController: UIViewController,LLPlayVMDelegate,UITableViewDataSource,UITableViewDelegate {

    var viewModel = LLPlayerVM()
    var tolView : LLPlayerView!
    var listView : LLListView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        viewModel.delegate = self
        loadUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.viewModel.playinfo(completeSuccess: {
            self.viewModel.playMusic()
        }, completeFailed: {
            self.showAlert(title: "提示", message: "没有找到地址，请重新进入", actionDone: { 
                self.dismiss()
            } )
        })

        self.viewModel.playkrc(completeSuccess: {
        }, completeFailed: {
            
        })
    }
    
    func loadUI() {
        tolView = LLPlayerView.returnPlayerView()
        tolView.frame = self.view.frame
        self.view.addSubview(tolView)
        tolView.tableView.delegate = self
        tolView.tableView.dataSource = self
        tolView.tableView.separatorStyle = .none
        tolView.tableView.register(ircTableViewCell.self, forCellReuseIdentifier: "irc")
        tolView.backBtn.addTarget(self, action: #selector(backBtnClick(sender:)), for: .touchUpInside)
        tolView.playBtn.addTarget(self, action: #selector(playBtnClick(sender:)), for: .touchUpInside)
        tolView.nextBtn.addTarget(self, action: #selector(next(sender:)), for: .touchUpInside)
        tolView.lastBtn.addTarget(self, action: #selector(last(sender:)), for: .touchUpInside)
        tolView.downLoadBtn.addTarget(self, action: #selector(downLoadMusic(sender:)), for: .touchUpInside)
        tolView.listBtn.addTarget(self, action: #selector(listBtnClick(sender:)), for: .touchUpInside)
    }
    
    func backBtnClick(sender:UIButton) {
        dismiss()
    }
    
    func dismiss(){
        self.viewModel.timer.invalidate()
        self.viewModel.stop()
        self.viewModel.delegate = nil
        self.dismiss(animated: true) {
            
        }
    }
    
    func last(sender:UIButton){
        self.viewModel.last()
    }
    
    func next(sender:UIButton){
        self.viewModel.next()
    }
    
    func playBtnClick(sender:UIButton) {
        sender.isSelected = !sender.isSelected
        self.viewModel.pause()
    }
    
    func didfinishCurrentValue(duration: String) {
        tolView.curLabel.text = duration
    }
    
    func didfinishTotalValue(duration: String) {
        tolView.druLabel.text = duration
    }
    
    func progressValue(float: Float) {
        tolView.progressSlider.setValue(float, animated: true)
    }
    
    func didfinishGetSongName(songname: String, fileName: String) {
        self.tolView.songNameLabel.text = songname
        self.tolView.fileNameLabel.text = fileName
    }
    
    // MARK: 滚动歌词
    func updateTable(indexPath: IndexPath) {
        tolView.tableView.reloadData()
        tolView.tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
    }
    
    func updateTableView() {
        tolView.tableView.reloadData()
    }
    
    // MARK: tableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == tolView.tableView {
            return self.viewModel.wordArr.count
        } else{
            return self.viewModel.numofRowsInListtableView().count
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == tolView.tableView {
            let cell = tableView.dequeueReusableCell(withIdentifier: "irc", for: indexPath) as! ircTableViewCell
            cell.contentLabel?.text = self.viewModel.wordArr[indexPath.row]
            cell.backgroundColor = .clear
            cell.selectionStyle = .none
            if self.viewModel.indexPath != nil {
                if self.viewModel.indexPath == indexPath{
                    cell.contentLabel?.textColor = .red
                    return cell
                }
            }
            cell.contentLabel?.textColor = .black
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "listcell", for: indexPath)
            cell.textLabel?.text = (self.viewModel.numofRowsInListtableView()[indexPath.row] as! String)
            return cell
        }
    }
    deinit {
        print("playMusic deinit")
    }
    
    func showAlert(title : String,message : String, actionDone: @escaping () -> Void) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let alertAction = UIAlertAction(title: "确定", style: .default) { (action) in
            actionDone()
        }
        alert.addAction(alertAction)
        self.present(alert, animated: true, completion: nil)
    }
    
    func downLoadMusic(sender : UIButton) {
        self.viewModel.downLoadMusic { (progress) in
            print("已下载 ：", progress)
        }
    }
    
    func listBtnClick(sender : UIButton) {
        listView = LLListView.returnLLListView()
        listView.frame = CGRect(x: 0, y: SCREENHEIGHT - 300, width: SCREENWIDTH, height: 300)
        self.view.addSubview(listView)
        listView.listTableView.delegate = self
        listView.listTableView.dataSource = self
        listView.listTableView.register(UITableViewCell.self, forCellReuseIdentifier: "listcell")
    }

}

class ircTableViewCell: UITableViewCell {
    var contentLabel : UILabel?
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        loadUI()
    }
    
    func loadUI() {
        contentLabel = UILabel()
        contentLabel?.textAlignment = .center
        contentLabel?.font = UIFont.systemFont(ofSize: 12)
        self.contentView.addSubview(contentLabel!)
        contentLabel?.snp.makeConstraints({ (make) in
            make.top.bottom.left.right.equalTo(self.contentView)
        })
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
